package com.example.crm.controller;

import com.example.crm.entity.Users;
import com.example.crm.service.UsersService;
import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.Optional;

@RestController
@RequestMapping("/api/users")//这个控制器的所有访问方法都必须以括号里的开头
public class UserController {

    @Autowired//使其只处理网络请求，不关心业务逻辑
    private UsersService usersService;

    @PostMapping("/register")
    public ResponseEntity<?> registerUser(@RequestBody Users user) {//前解析json数据，后填充到user内
        try {
            Users registeredUser = usersService.register(user);
            registeredUser.setPassword(null); // 防止密码泄露
            return ResponseEntity.ok(registeredUser);//返回200ok状态码
        } catch (IllegalStateException e) {//如果用户名已存在
            return ResponseEntity.status(HttpStatus.CONFLICT).body(e.getMessage());//返回409conflict
        }
    }

    @PostMapping("/login")
    public ResponseEntity<?> loginUser(@RequestBody LoginRequest loginRequest) {//登录所需要的东西不如注册需要的东西多，所以新建一个内部类
        Optional<Users> userOptional = usersService.login(loginRequest.getUsername(), loginRequest.getPassword());
        if (userOptional.isPresent()) {
            Users user = userOptional.get();
            user.setPassword(null); //防止密码泄露
            return ResponseEntity.ok(user);//登录成功
        } else {
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("Invalid username or password");
        }
    }

    @Data
    static class LoginRequest {
        private String username;
        private String password;
    }
}
